<?php

/**
 * @author charley
 * @copyright 2010
 */

if (!defined('IN_IMBA')) exit('Access Denied.');

require_once (IMBA_LIB . 'database/database.class.php');

class DBMysqli implements Database
{

	private $conn = array();
	private static $id = 0;
	private $resultArray = array();
	private $currentConn = 0;
	private $tablepre = '';

	public function __construct($configFile)
	{

		if (!file_exists(IMBA_CONFIG_DIR . 'db.conf.php'))
		{
			header('Location: install/re.config.php');
		}
		$this->currentConn = $this->create_new_conn($configFile);
		//Clear the config array, for security reasons.???
	}
	/**
	 * @name __destruct
	 * @author charleychaoyi
	 **/
	public function __destruct()
	{
		foreach ($this->conn as $tempID => $tempConn)
		{
			$this->destroy_conn($tempID);
		}
	}

	/**
	 * @name destroy_conn
	 * @author wrongway
	 */
	function destroy_conn($id)
	{
		if (isset($this->resultArray[$id]) && is_array($this->resultArray[$id]))
		{
			foreach ($this->resultArray[$id] as $qname)
			{
                //echo $qname->num_rows;
				$qname->free();
			}
            $this->resultArray[$id] = array();
		}
		if (isset($this->conn[$id])) @$this->conn[$id]->close();
	}

	/**
	 * @name query
	 * @author charleychaoyi, deltamaster
	 * @description Accept a SQL statement and execute it, save the result set if exist to the result set array.
	 * @parameter
	 *   string $sql: The SQL statement to execute.
	 *   string $query: The identifier of the result set, leave it empty if you do not want to save it.
	 * @return bool
	 * @data 2011-4-16
	 */
	public function query($sql, $query = '')
	{
		if (isset($this->resultArray[$this->currentConn][$query]))
		{
			$this->free_result($query);
		}
		$result = $this->conn[$this->currentConn]->query($sql);
		if ($result instanceof mysqli_result)
		{
			$this->resultArray[$this->currentConn][$query] = $result;
			return true;
		}
		else
		{
			return $result;
		}
	}
	/**
	 * @name free_result
	 * @auther wrongway
	 * */
	public function free_result($query)
	{
		$this->resultArray[$this->currentConn][$query]->free();
        unset($this->resultArray[$this->currentConn][$query]);
	}
	/**
	 * @name switch_conn
	 * @auther wrongway
	 * */
	public function switch_conn($id)
	{

		if ($id == $this->currentConn)
		{
			//echo "already connected!";
			return;
		}
		else
		{
			if (isset($this->conn[$id]))
			{
				$this->currentConn = $id;
				return true;
			}
			else  return false;
		}
	}

	/**
	 * @name CreateNewConn
	 * @author LittleZhi
	 * @description Create a new connection to the user.
	 * @parameters 
	 *  array $configFile : The information which user provide.
	 * @date 2010-12-04
	 * */
	public function create_new_conn($configFile)
	{
		$dbConfig = include ($configFile);
		try
		{
			@$this->conn[self::$id] = new mysqli($dbConfig['host'], $dbConfig['user'], $dbConfig['password'], $dbConfig['schema'], $dbConfig['port']);
			$this->tablepre = $dbConfig['tablepre'];
			if (mysqli_connect_errno())
			{
				$error = 'Can not connect the database';
				throw new ImbaException(E_DB_CONNECT);
			}
			else
			{
				$this->conn[self::$id]->set_charset('utf8');
				self::$id++;
				return self::$id - 1;
			}
		}
		catch (ImbaException $e)
		{
			$e->IncludeExceptionHandlerStop();
		}
	}

	/**
	 * @name fetch_array
	 * @author LittleZhi
	 * @description Fetch a result row as an associative, a numeric array, or both.
	 * @parameters 
	 *   string $query: Determine which result set to operate on.
	 *   int $result_type: Determine the type of the result, accept MYSQLI_NUM, MYSQLI_ASSOC, MYSQLI_BOTH
	 * @return array : return a certain array or false if there are no more rows.  
	 * @date 2010-12-04
	 * */
	function fetch_array($query, $result_type = MYSQLI_ASSOC)
	{
		if (isset($this->resultArray[$this->currentConn][$query])) return $this->resultArray[$this->currentConn][$query]->fetch_array($result_type);
		else  return false;
	}

	/**
	 * @name num_rows
	 * @author LittleZhi
	 * @description give out the number of the rows a result has.
	 * @parameters mysqli_result $query : a SQL result.
	 * @return int : the number of the rows or false on failure.  
	 * @date 2010-12-04
	 * */
	function num_rows($query)
	{
		if (isset($this->resultArray[$this->currentConn][$query])) return $this->resultArray[$this->currentConn][$query]->num_rows;
		else  return 0;
	}

	/**
	 * @name last_insert_id
	 * @author charleychaoyi
	 * @description Return the value of last affected auto increment value in the database.
	 * @parameter void
	 * @return int: The value of last affected auto increment value in the database.
	 * @data 2010-12-04
	 * @copyright 2010
	 */
	function last_insert_id()
	{
		return $this->conn[$currentConn]->insert_id;
	}
	
	function __get($name)
	{
		if ($name == 'tablepre') return $this->tablepre;
	}

}

?>